package com.ruicar.afs.cloud.workflow.api.util;

import com.ruicar.afs.cloud.workflow.api.cachebean.FlowMappingInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.Assert;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Function;
import java.util.stream.Collectors;

@Slf4j
public final class FlowMappingHelper {
    private static final Lock lock = new ReentrantLock();
    private static final Map<String, FlowMappingInfo> CACHE_SYNC_DATA = new HashMap<>();
    private static final Map<String, FlowMappingInfo> CACHE_MAPPING = new HashMap<>();

    public static void setConfigMapping(List<FlowMappingInfo> flowMappings) {
        lock.lock();
        try {
            CACHE_SYNC_DATA.putAll(flowMappings.stream().collect(Collectors.toMap(FlowMappingInfo::getAfsConfigKey, Function.identity())));
            CACHE_MAPPING.putAll(flowMappings.stream().collect(Collectors.toMap(FlowMappingInfo::getServiceId, Function.identity())));
        } finally {
            lock.unlock();
            log.info("当前配置流程映射信息{}", CACHE_SYNC_DATA);
        }
    }

    public static String getServiceId(String afsConfigKey) {
        lock.lock();
        try {
            Assert.isTrue(StringUtils.isNotEmpty(afsConfigKey), "流程映射key不能为空");
            Assert.isTrue(CACHE_SYNC_DATA.containsKey(afsConfigKey), "流程映射key" + afsConfigKey + "未配置");
            return CACHE_SYNC_DATA.get(afsConfigKey).getServiceId();
        } finally {
            lock.unlock();
        }
    }

    public static String getAfsKey(String serviceId) {
        lock.lock();
        try {
            Assert.isTrue(StringUtils.isNotEmpty(serviceId), "serviceId不能为空");
            return CACHE_MAPPING.get(serviceId) == null ? "" : CACHE_MAPPING.get(serviceId).getAfsConfigKey();
        } finally {
            lock.unlock();
        }
    }
    public static FlowMappingInfo getFlowMapping(String serviceId) {
        lock.lock();
        try {
            Assert.isTrue(StringUtils.isNotEmpty(serviceId), "serviceId不能为空");
            return CACHE_MAPPING.get(serviceId) == null ? null: CACHE_MAPPING.get(serviceId);
        } finally {
            lock.unlock();
        }
    }

    public static List<String> autoProcess(String serviceId){
        lock.lock();
        try {
            Assert.isTrue(StringUtils.isNotEmpty(serviceId), "serviceId不能为空");
            return CACHE_MAPPING.get(serviceId) == null ? new ArrayList<>() : CACHE_MAPPING.get(serviceId).getAutoTryResolverType();
        } finally {
            lock.unlock();
        }
    }
}
